<?php
/**
 * 属性分组管理
 * @author Mortimer He <mortimerhe@163.com>
 */
namespace Manage\Controller;
use Common\Library\Page;
class AttributeGroupController extends CommonController{
	private $msg=array();
	private $Model;
	function _initialize(){
		parent::_initialize();
		$this->Model=D('AttributeGroup');
	}
	public function index(){
		if(!$this->checkPermission('AttributeGroup')) $this->jump();
		$count=$this->Model->getCount();
		$Page=new Page($count,C('CONFIG_LIMIT_MANAGE'));
		$data['start']=$Page->firstRow;
		$data['limit']=$Page->listRows;
		$Page->setConfig('header',L('page_header'));
		$Page->setConfig('theme',L('page_theme'));
		$list=$this->Model->getAttrGroups($data);
		$show=$Page->show();
		$url['p']=I('get.p','');
		$this->assign('page',$show);
		$this->assign('url',$url);
		$this->assign('list',$list);
		$this->display();
	}
	public function oper($attribute_group_id=0){
		if(!$attribute_group_id && !$this->checkPermission('AddAttributeGroup')) $this->jump();
		$attribute_group=$this->Model->getById($attribute_group_id);
		if($attribute_group_id && empty($attribute_group)) $this->jump(L('error_404'));
		if(IS_POST){
			$attribute_group=I('post.');
			if($this->validateForm($attribute_group_id)){
				$this->Model->operAttributeGroup($attribute_group,$attribute_group_id);
				session('success',$attribute_group_id?L('success_edit'):L('success_add'));
				$url['p']=I('get.p','');
				$this->redirect('index',$url);
			}else{
				if(!isset($this->msg['warning'])) $this->msg['warning']=L('error_warning');
			}
		}
		$this->assign('attribute_group',$attribute_group);
		$this->assign('msg',$this->msg);
		$this->assign('languages',get_langs());
		$this->display();
	}
	public function del(){
		if($this->checkPermission('DeleteAttributeGroup')){
			if($this->validateDelete()){
				$ids=I('post.selected');
				$count=0;
				foreach ($ids as $attribute_group_id) {
					$count += $this->Model->del($attribute_group_id);
				}
				session('success',L('success_delete',array('count'=>$count)));
			}else{
				session('danger',L('error_delete'));
			}
		}
		$this->redirect('index');

	}
	private function validateForm($attribute_group_id){
		if($attribute_group_id && !$this->checkPermission('EditAttributeGroup')) {
			$this->msg['warning']=L('error_not_permission');
			return !$this->msg;
		}
		$data=I('post.');
		$Model=M('AttributeGroupDescription');
		foreach ($data['attribute_group_description'] as $k => $v) {
			if(mb_strlen($v['name'])>64 || mb_strlen($v['name'])<2){
				$this->msg['name'][$k]=L('error_name');
			}else{
				$map=array(
					'language_id'	=> $k,
					'attribute_group_id'=>array('neq',$attribute_group_id),
					'name'			=>	$v['name']
					);
				if($Model->where($map)->find()){
					$this->msg['name'][$k]=L('error_name_exist');
				}
			}
		}
		return !$this->msg;
	}
	private function validateDelete(){
		return true;
	}
}